const express = require('express');
const router = express.Router();
const moment = require('moment');
const { pool } = require('../config/db');

// 记录网站访问量
router.post('/visit', async (req, res) => {
  try {
    const conn = await pool.getConnection();
    await conn.beginTransaction();

    try {
      // 更新访问量和最后访问时间
      await conn.execute(
        'UPDATE website_stats SET visits = visits + 1, last_visit_time = NOW() WHERE id = 1'
      );

      await conn.commit();
      conn.release();

      res.json({
        code: 200,
        message: '访问量记录成功'
      });
    } catch (error) {
      await conn.rollback();
      conn.release();
      throw error;
    }
  } catch (error) {
    console.error('记录访问量失败:', error);
    res.status(500).json({
      code: 500,
      message: '记录访问量失败'
    });
  }
});

// 获取网站访问量
router.get('/visits', async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT visits FROM website_stats WHERE id = 1');
    
    res.json({
      code: 200,
      data: {
        visits: rows[0]?.visits || 0
      }
    });
  } catch (error) {
    console.error('获取访问量失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取访问量失败'
    });
  }
});

// 获取网站启动时间
router.get('/start-time', async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT start_time FROM website_stats WHERE id = 1');
    
    res.json({
      code: 200,
      data: {
        startTime: moment(rows[0]?.start_time).format('YYYY-MM-DD HH:mm:ss')
      }
    });
  } catch (error) {
    console.error('获取启动时间失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取启动时间失败'
    });
  }
});

// 获取网站运行时间
router.get('/running-time', async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT start_time FROM website_stats WHERE id = 1');
    const startTime = moment(rows[0]?.start_time);
    const now = moment();
    const duration = moment.duration(now.diff(startTime));

    res.json({
      code: 200,
      data: {
        days: duration.days(),
        hours: duration.hours(),
        minutes: duration.minutes(),
        seconds: duration.seconds()
      }
    });
  } catch (error) {
    console.error('获取运行时间失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取运行时间失败'
    });
  }
});

module.exports = router;